//
//  DetailCell.swift
//  DetailList
//
//  Created by mayuncui on 2020/9/23.
//  Copyright © 2020 Myc. All rights reserved.
//

import UIKit
import FlexLayout
import SDWebImage

protocol DetailItemCellDelegate {
    /// 单元格中图片点击事件
    /**
     - index: 点击的图片索引
     - imgArr: 图片数组,传递的是urlStr
     - link: 超链接网址
     */
    func DetailItemCellImgClick(index:Int,imgArr:[String])
    func DetailItemCellContentLinkClick(link:String)

}

class DetailItemCell: DetailFlexBaseCell {

    var content = UILabel()
    var imageContent = UIView()
    
    ///代理设置属性
    var delegate:DetailItemCellDelegate?

    //数据模型
    var dataModel: DataModel? {
        didSet{
            content.text = dataModel?.content
            
            if dataModel?.type == ContentType.text_link {
                let tap = UITapGestureRecognizer.init(target: self, action: #selector(contentTapAction))
                content.usInfo = ["link": dataModel?.link ?? ""]
                //打开用户交互
                content.isUserInteractionEnabled = true
                content.addGestureRecognizer(tap)
            }else{
                content.isUserInteractionEnabled = false
            }
            content.flex.isIncludedInLayout = dataModel?.content?.count ?? 0 > 0 ? true : false
            for view in self.imageContent.subviews {view.removeFromSuperview()}
            guard let imageUrls = dataModel?.imgUrls else { return }
            if imageUrls.count > 0 {
                for index in 0..<imageUrls.count {
                    let imgV = UIImageView()
                    imgV.contentMode = .scaleToFill
                    imgV.backgroundColor = .gray
                    
                    switch imageUrls.count {
                    case 1:
                        self.imageContent.flex.direction(.row).define({
                            $0.addItem(imgV).width(img1Width).height(img1Height)
                        })
                    case 2:
                        self.imageContent.flex.direction(.row).define({
                            $0.addItem(imgV).marginLeft(imgSpace*CGFloat(index)).width(img2Width).height(img2Height)
                        })
                    case 3:
                        self.imageContent.flex.direction(.row).define({
                            $0.addItem(imgV).marginLeft(imgSpace).marginTop((imgSpace + imgWidth * 4 / 3) *  CGFloat( index / 3)).width(imgWidth).height(imgWidth * 4 / 3)
                        })
                    default:
                        self.imageContent.flex.direction(.row).define({
                            if index < 2 {
                                $0.addItem(imgV).marginLeft(imgSpace).marginTop((imgSpace + imgWidth * 4 / 3) *  CGFloat( index / 3)).width(imgWidth).height(imgWidth * 4 / 3)
                            }
                            //当要展示的图片多余三张时，展示三张，最后一张图上显示更多提示
                            if index == 2 {
                                $0.addItem(imgV).define({
                                    $0.addItem(UILabel().with({
                                        $0.text = "More"
                                        $0.textColor = .gray
                                        $0.textAlignment = .center
                                        $0.backgroundColor = UIColor(white: 0, alpha: 0.6)
                                        $0.isUserInteractionEnabled = true
                                    })).grow(1).shrink(1)
                                }).marginLeft(imgSpace).marginTop((imgSpace + imgWidth * 4 / 3) *  CGFloat( index / 3)).width(imgWidth).height(imgWidth * 4 / 3)
                            }
                        })
                    }
                    imgV.sd_setImage(with: URL(string:imageUrls[index]), placeholderImage: UIImage(named: "socute"))
                    imgV.tag = 100 + index
                    let tap = UITapGestureRecognizer.init(target: self, action: #selector(imgTapAction))
                    //打开用户交互
                    imgV.isUserInteractionEnabled = true
                    imgV.addGestureRecognizer(tap)
                }
                self.imageContent.flex.layout()
                self.contentView.flex.layout()
            }
           
        }
        
    }
    
    // MARK: -------- TapAction --------
    @objc func imgTapAction(tap:UITapGestureRecognizer) {
        let  index = (tap.view?.tag)!  - 100 //获取当前点击的图片索引....
           ///调用代理方法
        self.delegate?.DetailItemCellImgClick(index: index, imgArr: (dataModel?.imgUrls)!)
    }
    
    
    @objc func contentTapAction(tap:UITapGestureRecognizer) {
        //获取当前点击的链接
        guard let str = tap.view?.usInfo?["link"] as? String else { return  }
        ///调用代理方法
        self.delegate?.DetailItemCellContentLinkClick(link: str)
        
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        configUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///cell布局
    func configUI() {
        contentView.flex.padding(10, 15, 30, 15).define({
            $0.addItem(content.with({
                $0.numberOfLines = 0
                $0.textAlignment = .left
                $0.textColor = .black
                $0.font = UIFont(name: "PingFangSC-Regular", size: 15)
            })).marginBottom(10).grow(1).shrink(1)
            $0.addItem(imageContent).grow(1).shrink(1)
        })
    }

}


//cell布局基类
class DetailFlexBaseCell: UITableViewCell {
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        contentView.flex.layout(mode: .adjustHeight)
        return contentView.frame.size
    }
    
    override func layoutSubviews() {
        contentView.flex.layout(mode: .adjustHeight)
    }
    
    func clearBackground() {
        backgroundView = UIImageView()
        backgroundColor = .clear
    }
}
